package com.chanjiedata.changbs.module.count;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.adapter.TaijunAdapter;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.dialog.SelectMonthDialog;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Mystock;
import com.chanjiedata.changbs.proto.Statistics;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

/**
 * 文件名 : CountFiveActivity
 * 创建者 : MangoWang
 * 创建日期 : 2020/1/2 16:01
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class CountFiveActivity extends BaseActivity {


    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.tv_total_tai_jun)
    TextView tvTotalTaiJun;
    @BindView(R.id.tv_total_tai_jun_shu)
    TextView tvTotalTaiJunShu;
    @BindView(R.id.mPieChart)
    PieChart mPieChart;

    private ArrayList<PieEntry> pieEntries = new ArrayList<>();
    private String[] pieColor;
    private String search_time_end ;
    private String goods_id = "";
    private List<Mystock.myMachine.List> datas = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_five_count);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        ButterKnife.bind(this);
        tvTitle.setText(getIntent().getStringExtra("name")+"的台均");
        search_time_end = getIntent().getStringExtra("time");
        tvSelectTime.setText(search_time_end);
        pieColor = getResources().getStringArray(R.array.array_seven_color);
        initListener();
        initPerChat();
        initXinahaoData();
    }

    private void initListener() {
        tvSelectTime.setOnClickListener(v -> {
            SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mContext);
            builder.setOnDialogClickListener((view, month) -> {
                search_time_end = month;
                tvSelectTime.setText(search_time_end);
                loadPerChartData();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());
        });

        backTv.setOnClickListener(view -> finish());
    }


    private void initPerChat() {
        mPieChart.setRotationEnabled(false);// 可以手动旋转
        mPieChart.setUsePercentValues(false);//显示成百分比
        mPieChart.setDrawEntryLabels(false);
        mPieChart.setTouchEnabled(false);
        mPieChart.setDrawCenterText(false);

        mPieChart.getDescription().setEnabled(false); //取消右下角描述
        //去掉半透明
        mPieChart.setTransparentCircleAlpha(0);
        mPieChart.getLegend().setEnabled(true);


        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setFormSize(10);                      //设置图例的大小
        l.setFormToTextSpace(10f);              //设置每个图例实体中标签和形状之间的间距
        l.setForm(Legend.LegendForm.CIRCLE); //设置图例的形状

        l.setFormSize(13);                      //设置图例的大小

        l.setTextSize(13f);                      //设置图例标签文本的大小

        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);

        l.setXOffset(30);                      //设置比例块Y轴偏移量


        l.setXEntrySpace(30);

        l.setWordWrapEnabled(true);
    }

    //设置tablayout
    /**
     * 初始化折线图tab
     */
    private void initTabLayout() {
        for(int i=0;i<datas.size();i++){
            tabLayout.addTab(tabLayout.newTab());
            tabLayout.getTabAt(i).setText(datas.get(i).getGoodsSerial());
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.0f,1.15f,tab.view);
                goods_id = datas.get(tab.getPosition()).getGoodsId();
                loadPerChartData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if(tab==null|| tab.getText() == null)
                {
                    return;
                }
                scaleAnima(1.15f,1.0f,tab.view);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabLayout.getTabAt(getIntent().getIntExtra("position",0)).select(); //默认选中某项放在加载viewpager之后
//        scaleAnima(1.0f,1.15f,tabLayout.getTabAt().view);
    }

    private void scaleAnima(float v,float v2, TabLayout.TabView title) {
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(
                v, v2, v, v2,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(100);//动画持续时间
        animationSet.addAnimation(scaleAnimation);//保存动画效果到。。
        animationSet.setFillAfter(true);//结束后保存状态
        title.startAnimation(animationSet);//设置给控件

    }

    private void loadPerChartData() {
        showProgress();
        Statistics.get_sn_average.Builder builder = Statistics.get_sn_average.newBuilder();
        builder.setMemberId(getIntent().getStringExtra("member_id")).setMonth(search_time_end).setGoodsId(goods_id);
        NetworkManager.INSTANCE.post(Apis.get_sn_average, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                hideProgress();
                Statistics.get_sn_average datas = Statistics.get_sn_average.parseFrom(bytes);
                List<Statistics.basis> lists = datas.getAverageList();
                setPerChartData(lists, datas.getAverageAmount(), datas.getNum());
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });
    }


    private void setPerChartData(List<Statistics.basis> lists, String average_amount, String num) {
        pieEntries.clear();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        tvTotalTaiJun.setText(String.format("￥%s", average_amount));
        tvTotalTaiJunShu.setText(num + "台");
        for (int i = 0; i < lists.size(); i++) {
            colors.add(Color.parseColor(pieColor[i]));
            if (Float.valueOf(num) == 0) {
                pieEntries.add(new PieEntry(1, lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            } else {
                pieEntries.add(new PieEntry(Float.valueOf(lists.get(i).getNum()), lists.get(i).getName() + " " + lists.get(i).getNum() + "台"));
            }
        }
        PieDataSet dataSet = new PieDataSet(pieEntries, "");
        //设置饼状Item之间的间隙
        dataSet.setSliceSpace(2f);
        //数据和颜色
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setDrawValues(false);
        mPieChart.setData(data);
        mPieChart.animateXY(500,500);
    }

    private void initXinahaoData() {
        NetworkManager.INSTANCE.post(Apis.myMachine, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                datas = Mystock.myMachine.parseFrom(bytes).getListList();
                goods_id = datas.get(getIntent().getIntExtra("position",0)).getGoodsId();
                initTabLayout();
                loadPerChartData();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }
}
